package joymouse;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
import net.java.games.input.Controller;

/**
 * Singleton responsible for managing all running device controllers.
 *
 * @author Ben Wolsieffer
 */
public class ControllerManager {

    private static HashMap<Controller, ArrayList<DeviceController>> controllers = new HashMap<>();

    /**
     * Adds a {@link DeviceController} to the list of running device
     * controllers.
     *
     * @param dc The device controller
     * @see DeviceController
     */
    public static void addDeviceController(DeviceController dc) {
        Controller cont = dc.getController();
        if (!controllers.containsKey(cont)) {
            ArrayList<DeviceController> arr = new ArrayList<>();
            arr.add(dc);
            controllers.put(cont, arr);
        } else {
            controllers.get(cont).add(dc);
        }
    }

    /**
     * Starts the manager. The manager blocks and runs in the thread it was
     * started in.
     */
    public static void run() {
        for (;;) {
            for (Entry<Controller, ArrayList<DeviceController>> ent : controllers.entrySet()) {
                ent.getKey().poll();
                for (DeviceController dc : ent.getValue()) {
                    dc.run();
                }
            }
            try {
                Thread.sleep(1);
            } catch (InterruptedException ex) {
            }
        }
    }
}
